package db.dao;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.HashMap;

public class BeanFactory {

	public static Object getObj(String bean, ResultSet resultSet)
			throws Exception {
		HashMap fields = new HashMap();
		Object o = Class.forName(bean);
		Field[] ff = ((Class) o).getDeclaredFields();
		Method[] mm = ((Class) o).getDeclaredMethods();
		//System.out.println("Fields:");
		for (Field f : ff) {
			Class clazz = f.getType();
			fields.put(f.getName(), f.getType().toString());
		}

		//.out.println("methods:");
		ResultSetMetaData rsmd = resultSet.getMetaData();

		int columnCount = rsmd.getColumnCount();


		Object res = Class.forName(bean).newInstance();
		for (int i = 1; i < columnCount + 1; i++) {
			String name = rsmd.getColumnName(i);
			if (!fields.containsKey(name))
				throw new Exception("Field " + name
						+ " of result set is not into Bean " + o.toString());
			String getmethod = "set" + name.substring(0, 1).toUpperCase()+name.substring(1);

			String filedType = (String) fields.get(name);
			Class type = getPrimitiveType(filedType);
			//System.out.println(type.getClass());
			Method method = ((Class) o).getMethod(getmethod,  type );
			if (type.toString().equalsIgnoreCase("class java.lang.String")) {
				method.invoke(res, resultSet.getString(name).trim() );
			}
			if (type.toString().equalsIgnoreCase("int")) {
				method.invoke(res,resultSet.getInt(name) );
			}
			if (type.toString().equalsIgnoreCase("long")) {
				method.invoke(res,resultSet.getLong(name));
			}
			if (type.toString().equalsIgnoreCase("double")) {
				method.invoke(res,resultSet.getDouble(name));
			}
			//System.out.println(name);
		}

		return res;
	}

	public static Class getPrimitiveType(String name) {
		if (name.equals("byte"))
			return Byte.TYPE;
		if (name.equals("short"))
			return Short.TYPE;
		if (name.equals("int"))
			return Integer.TYPE;
		if (name.equals("long"))
			return Long.TYPE;
		if (name.equals("char"))
			return Character.TYPE;
		if (name.equals("float"))
			return Float.TYPE;
		if (name.equals("double"))
			return Double.TYPE;
		if (name.equals("boolean"))
			return Boolean.TYPE;
		if (name.equals("void"))
			return Void.TYPE;
		if(name.equals("class java.lang.String"))
			return String.class;

		throw new IllegalArgumentException();
	}
}
